package wsz.demo;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @author wsz
 * @date 2021/11/27 17:35
 **/
public class NettyServer {

    public static void main(String[] args) throws InterruptedException {
        //1.创建bossgroup
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        //2.创建workgroup
        NioEventLoopGroup workGroup = new NioEventLoopGroup();
        //3. 创建服务端启动助手
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        //4.设置bossgroup线程组和workgroup线程组
        serverBootstrap.group(bossGroup, workGroup)
                .channel(NioServerSocketChannel.class)  //5.设置服务端通道实现未NIO
                .option(ChannelOption.SO_BACKLOG, 128)  //6.参数设置
                .childOption(ChannelOption.SO_KEEPALIVE, Boolean.TRUE)  //参数设置
                .childHandler(new ChannelInitializer<SocketChannel>() { //7.创建一个通道初始化对象
                    @Override
                    protected void initChannel(SocketChannel channel) throws Exception {
                        // 添加解码器
//                        channel.pipeline().addLast("messageDecoder", new MessageDecoder());
                        // 添加编码器
//                        channel.pipeline().addLast("messageEncoder", new MessageEncoder());
                        // 编解码器
                        channel.pipeline().addLast("messageCodec", new MessageCodec());
                        //8. 向pieline中添加自定义业务处理handler
                        channel.pipeline().addLast(new ServerHandler());
                    }
                });
        // 9.启动服务并绑定端口，同时将异步改为同步
//        ChannelFuture future = serverBootstrap.bind(9999).sync();
        // 默认异步：先打印 服务器启动成功 -> 端口绑定成功
        ChannelFuture future = serverBootstrap.bind(9999);
        future.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                if (channelFuture.isSuccess()) {
                    System.out.println("端口绑定成功");
                } else {
                    System.out.println("端口绑定失败");
                }
            }
        });
        System.out.println("服务端启动成功....");
        // 10.关闭通道，关闭连接池
        future.channel().closeFuture().sync();
        bossGroup.shutdownGracefully();
        workGroup.shutdownGracefully();
    }
}
